package top.oauth2.server.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import top.oauth2.common.result.CommonResult;
import top.oauth2.server.entity.Oauth2TokenDto;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

/**
 * @author xphu
 * @version 1.0
 * @date 2021/8/26 16:33
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Oauth2登录认证
     */
    @PostMapping(value = "/token")
    public CommonResult<Oauth2TokenDto> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters, HttpServletRequest request) throws HttpRequestMethodNotSupportedException {
        String grantType = parameters.get("grant_type");

        if (!"refresh_token".equals(grantType)){
            // 获取验证码
            String codeKey = parameters.get("codeKey");
            String inputCode = parameters.get("code");
            String username = parameters.get("username");
            String[] strings = username.split(":");
            String type = null;
            if (strings != null && strings.length >1 ){
                type = strings[0];
            }
            if (StringUtils.isEmpty(codeKey)){
                return CommonResult.failed("验证码key不能为空！");
            }

            if (StringUtils.isEmpty(inputCode)){
                return CommonResult.failed("验证码不能为空！");
            }

            String code = (String) redisTemplate.opsForValue().get(codeKey);
            redisTemplate.delete(codeKey);
            if (StringUtils.isEmpty(code)){
                return CommonResult.failed("未申请验证码！");
            }

            if (!code.equalsIgnoreCase(inputCode)){
                return CommonResult.failed("验证码不正确！");
            }
        }

        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead("Bearer ").build();
        return CommonResult.success(oauth2TokenDto);
    }

}
